<script setup lang="ts">
import Detail from './components/Detail.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import {computed, onMounted, ref} from 'vue'
import { useRoute } from 'vue-router'
import {ElRow, ElCol, ElScrollbar, ElMessage, UploadFile, ElMessageBox, ElSpace, ElDivider} from 'element-plus'
import {GroupType} from "@/types";
import {patientDetailApi} from "@/api/patient";
import {PatientType} from "@/api/patient/types";
import {CreatePictureForm, PictureType} from "@/api/picture/types";
import {PictureClassPatientType} from "@/api/pictureClass/types";
import {patientPictureTypeApi} from "@/api/pictureClass";
import {UploadFileForm} from "@/api/common/types";
import {uploadApi} from "@/api/common";
import {createPictureApi, deletePictureApi, printPictureApi} from "@/api/picture";
import {cloneDeep} from "lodash-es";
import PrintDialog from "./components/PrintDialog.vue";
import {CreateRecordForm} from "@/api/record/types";
import {createRecordApi} from "@/api/record";
import {useUserStoreWithOut as useUserStore} from "@/store/modules/user";
import {createImageViewer} from "@/components/ImageViewer";
import {getImgPath} from "@/utils/image";


const { query } = useRoute()

const userStore = useUserStore()

const currentRow = ref<Nullable<PatientType>>(null)
const str = query.id as string
const patient_id = parseInt(str)
const getPatientInfo = async () => {
  const res = await patientDetailApi(patient_id)
  currentRow.value = res.data
  // 提交记录
  const record: CreateRecordForm = {
    use_user: userStore.getUserInfo?.name as string,
    desc: 3,
    operate_account: userStore.getUserInfo?.account || "",
    patient_name: currentRow.value.name,
    patient_number: currentRow.value.patient_number,
    type: 1
  }
  await createRecordApi(record).finally(()=>printLoading.value = false)
}

getPatientInfo()
const openID = ref(0)
// 获取患者所有图片
const group = ref<PictureClassPatientType[]>([])
const checkedID = ref(0)
const getAllPicture = async ()=>{
  const res = await patientPictureTypeApi(patient_id)
  group.value = res.data
  console.log(res)
  checkedID.value = res.data[0].id
  switchOpenID()
}
getAllPicture()

const switchOpenID = ()=>{
  if (checkedID.value !== openID.value){
    openID.value = checkedID.value
  }else{
    openID.value = 0
  }
}

const imgIndex = ref(0)
const switchGroup = ({type, current})=>{
  let checked = false
  if (type === 'switch'){
    imgIndex.value = current
    return
  }
  // 查询当前group索引
  let index = group.value.findIndex(item => item.id === checkedID.value)
  if (type == 'next'){
    // 从当前索引开始往下找有图片的group
    console.log(index+1, group.value.length)
    for(let i = index+1; i < group.value.length; i++){
      if(group.value[i].pictures){
        checkedID.value = group.value[i].id
        checked = true
        break
      }
    }
  }else{
    // 往前找有图片的group
    for (let i = index-1 ; i >= 0; i --){
      if(group.value[i].pictures){
        checkedID.value = group.value[i].id
        checked = true
        break
      }
    }
  }
  // 找到了可以替换的图片组
  if (checked){
    imgIndex.value = type == 'prev' ? images.value.length - 1 : 0
    switchOpenID()
  }else{
    ElMessage.info("后面没有其他类型病历了")
  }
}

const images = computed(()=>{
  let imgArr: PictureType[] = []
  group.value.forEach(item => {
    if(item.id === checkedID.value){
      if (group.value.length){
        // 计算图片
        imgArr = item.pictures || []
      }
    }
  })
  return imgArr
})
const selectGroup = (item: GroupType)=>{
  checkedID.value = item.id
  imgIndex.value = 0
  switchOpenID()
}
const changeImgIndex = (index: number, group: GroupType)=>{
  console.log(group)
  if (group.id !== checkedID.value){
    checkedID.value = group.id
  }
  imgIndex.value = index
}
const uploading = ref(false)
const onUpload = async(file: UploadFile)=>{
  const params: UploadFileForm ={
    file: file.raw
  }
  uploading.value = true
  const res = await uploadApi(params).finally(()=>{
    uploading.value  = false
  })
  // 将图片进行创建
  let url = res.data.pop() as string
  const create: CreatePictureForm = {
    url: url,
    type_id: checkedID.value,
    patient_id: patient_id
  }
  const pic = await createPictureApi(create)
  const tmpGroup = cloneDeep(group.value)
  ElMessage.success('上传成功')
  tmpGroup.forEach(item => {
    if(item.id === checkedID.value){
      if(item.pictures){
        item.pictures?.push(pic.data)
      }else{
        item.pictures = [pic.data]
      }
    }
  })
  group.value = tmpGroup
}

const delImg = async ()=>{
  const pic = images.value[imgIndex.value]
  await ElMessageBox.confirm("确认删除选中的扫描件吗？", "提示")
  await deletePictureApi(pic.id)
  // 删除完成，将列表里面的同步删除
  const tmpGroup = cloneDeep(group.value)
  tmpGroup.forEach(item => {
    if(item.id === checkedID.value){
      item.pictures = item.pictures?.filter(p => p.id !== pic.id)
    }
  })
  group.value = tmpGroup
  ElMessage.success("删除成功")
}
const currentGroup = computed(():PictureClassPatientType=>{
  return group.value.find((item:PictureClassPatientType) => item.id === checkedID.value) as PictureClassPatientType
})

const printDialog = ref(false)

const onPrint = ()=>{
  printDialog.value = true
}
const printLoading = ref(false)
const printPic = async(formData: any)=>{
  if (!currentRow.value)return
  printLoading.value = true
  // 获取打印的图片
  const res = await printPictureApi(formData.pictures).finally(()=>printLoading.value = false)
  // 提交记录
  const record: CreateRecordForm = {
    use_user: formData.use_user,
    desc: formData.desc,
    operate_account: userStore.getUserInfo?.account || "",
    patient_name: currentRow.value.name,
    patient_number: currentRow.value.patient_number,
    type: 2
  }
  await createRecordApi(record).finally(()=>printLoading.value = false)
  // 开始生成打印
  generatePrintHtml(res.data.data)
}
const generatePrintHtml = (pics: PictureType[])=>{
  let html = ""
  pics.forEach(pic=>{
    html += `<div style="height: 100vh"><img style="width: 100vw" src="${pic.url}" alt="病例图片"></div>`;
  })
  html = `
    <html>
      <body>
        ${html}
      </body>
    </html>
  `
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);
  if (!iframe.contentDocument)return
  iframe.contentDocument.open();
  iframe.contentDocument.write(html);
  iframe.contentDocument.close();

  iframe.onload = function() {
    if (!iframe.contentWindow)return
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    setTimeout(() => {
      document.body.removeChild(iframe);
    }, 500);
  };

}
const openPreview = ()=>{
  // 获取当前分组
  const data = currentGroup.value
  const pics = data.pictures?.map(item=>getImgPath(item.url))
  createImageViewer({
    urlList: pics,
    initialIndex: imgIndex.value,
    title: data.name,
    onJump: (type, index)=>{
      // 跳转上/下一组
      switchGroup({type, current: index})
    },
  })
}
const height = ref(0)
const setHeight = ()=>{
  height.value = window.innerHeight - 185
}
setHeight()
</script>

<template>
  <ContentDetailWrap>
    <template #header v-if="currentRow">
<!--      <BaseButton @click="go(-1)">-->
<!--        返回-->
<!--      </BaseButton>-->
      <div class="header">
        <ElSpace>
          <strong>病历号:{{currentRow?.patient_number}}</strong><ElDivider direction="vertical"/>
          <strong>姓名:{{currentRow?.name}}</strong><ElDivider/><ElDivider direction="vertical"/>
          <strong>性别:{{currentRow?.gender === 1 ? '男' : '女'}}</strong><ElDivider direction="vertical"/>
          <strong>身份证:{{currentRow?.card_number}}</strong>
        </ElSpace>
        <ElSpace >
          <ElUpload
              ref="uploadRef"
              class="upload-demo"
              :auto-upload="false"
              :show-file-list="false"
              :multiple="true"
              @change="onUpload"
          >
            <slot name='trigger'>
              <BaseButton type="primary" :loading="uploading">上传图片</BaseButton>
            </slot>
          </ElUpload>
          <ElSpace>
            <BaseButton type="info" @Click="openPreview">病历预览</BaseButton>
            <BaseButton type="success" @click="onPrint">病历打印</BaseButton>
            <BaseButton type='danger' @click="delImg">删除该扫描件</BaseButton>
          </ElSpace>
        </ElSpace>
      </div>
    </template>
    <ElRow v-if="height" :gutter="10">
      <ElCol :span="4" >
        <ElScrollbar
          :height="height"
        >
          <div class="group">
            <div v-for="item in group" :key="item.id" >
              <div :class="{'item': true, 'active': checkedID === item.id}"@click="selectGroup(item)">
                <span>{{item.name}}</span>
                <div v-if="item.pictures">
                  {{openID === item.id ? '-' : '+'}}
                </div>
              </div>
              <template v-if="openID === item.id">
                <div :class="{'pic-index': true, 'checked': imgIndex === index && checkedID === item.id}" v-for="(pic, index) in item.pictures" :key="pic.url" @click="changeImgIndex(index, item)">第{{ index + 1 }}页</div>
              </template>
            </div>
          </div>
        </ElScrollbar>

      </ElCol>
      <ElCol :span="20">
        <Detail
            :current-group="currentGroup"
            :current-row="currentRow"
            :img-index="imgIndex"
            :images="images"
            :height="height"
            @onDelete="delImg"
            @onSwitchGroup="switchGroup"
        />
      </ElCol>
    </ElRow>
    <PrintDialog
        v-model="printDialog"
        :group="group"
        @confirm="printPic"
        :printLoading="printLoading"
    />
  </ContentDetailWrap>
</template>

<style scoped lang="less">
.group{
  display: grid;
  grid-row-gap: 10px;
  height: 100%;
  position: sticky;
  .pic-index{
    margin-left: 10px;
    margin-top: 10px;
    font-size: 13px;
    cursor: pointer;
    transition: all linear .2s;
    &.checked{
      color: var(--el-color-primary);
    }
  }
  .item{
    padding: 10px;
    font-size: 14px;
    border-radius: 7px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: var(--left-menu-border-color);
    cursor: pointer;
    transition: all linear .2s;
    color: var(--el-text-color-regular);
    &.active{
      background-color: var(--el-color-primary);
      color: var(--el-color-white);
    }
  }
}
.header{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>